package com.abe.bathsystem.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.abe.bathsystem.utils.NormalUtils;
import com.abe.bathsystem.utils.SerialPortUtils;
import com.abe.libcore.BaseApplication;
import com.abe.libcore.utils.normal.CommonUtils;
import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.google.gson.Gson;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;

import android_serialport_api.SerialPort;

public class ManagerAPP extends BaseApplication {
    /**
     * 串口
     */
    private SerialPort ttys0_SerialPort = null;
    private SerialPort ttysOther_SerialPort = null;

    private static ManagerAPP application;
    private MessageReceiver mMessageReceiver;
    public static final String RESET_PUSH_SERVICE = "com.abe.bathsystem.reset.push";

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        initPush();
        registerMessageReceiver();
        ZXingLibrary.initDisplayOpinion(this);
        CrashReport.initCrashReport(getApplicationContext(), "85307b5397", true);
        //ANR捕捉
        new ANRWatchDog().setANRListener(new ANRWatchDog.ANRListener() {
            @Override
            public void onAppNotResponding(ANRError error) {
                CommonUtils.saveLocalLog("ANR", new Gson().toJson(error));
                NormalUtils.resetApp();
            }
        }).start();
    }

    private void initPush() {
        XGPushConfig.enableDebug(this, true);
        XGPushManager.registerPush(this, new XGIOperateCallback() {
            @Override
            public void onSuccess(Object data, int flag) {
                //token在设备卸载重装的时候有可能会变
                CommonUtils.w("TPush-注册成功，设备token为：" + data);
            }

            @Override
            public void onFail(Object data, int errCode, String msg) {
                CommonUtils.w("TPush-注册失败，错误码：" + errCode + ",错误信息：" + msg);
            }
        });
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        destroyMessageReceiver();
    }

    public static ManagerAPP getInstance() {
        if (null == application) {
            application = new ManagerAPP();
        }
        return application;
    }

    private void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(RESET_PUSH_SERVICE);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    private void destroyMessageReceiver() {
        if (mMessageReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
            mMessageReceiver = null;
        }
    }

    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getExtras() == null || TextUtils.isEmpty(intent.getAction()))
                return;
            switch (intent.getAction()) {
                case RESET_PUSH_SERVICE: {
                    initPush();
                }
                break;
            }
        }
    }

    public SerialPort getSerialPort(int type) throws SecurityException,
            IOException, InvalidParameterException {
        if (type == SerialPortUtils.SerialPort_ttys0) {
            if (ttys0_SerialPort == null) {
                ttys0_SerialPort = new SerialPort(new File(
                        SerialPortUtils.path_ttys0),
                        SerialPortUtils.baudRate, 0);
            }
            return ttys0_SerialPort;
        } else if (type == SerialPortUtils.SerialPort_ttysOther) {
            if (ttysOther_SerialPort == null) {
                ttysOther_SerialPort = new SerialPort(new File(ManagerLocalData.getSerialPort()),
                        SerialPortUtils.baudRate, 0);
            }
            return ttysOther_SerialPort;
        } else {
            return null;
        }
    }

    public void closeSerialPort(int type) {
        if (type == SerialPortUtils.SerialPort_ttys0
                && ttys0_SerialPort != null) {
            ttys0_SerialPort.close();
            ttys0_SerialPort = null;
        }
        if (type == SerialPortUtils.SerialPort_ttysOther
                && ttysOther_SerialPort != null) {
            ttysOther_SerialPort.close();
            ttysOther_SerialPort = null;
        }
    }
}